from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.http import Http404, HttpResponseRedirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail
from application.account.models import newlife_users
import os, datetime,commands,hashlib,random,re

# Create your views here.

def index(request):
    if request.user.is_authenticated():
        return render_to_response('index.html', locals(), context_instance=RequestContext(request))
    else:
        return render_to_response('account/login.html', context_instance=RequestContext(request))

@csrf_exempt
def signin(request):
    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            return render_to_response('notice/inactivation.html')
    else:
        return render_to_response('notice/login_error.html')

def signout(request):
    logout(request)
    return HttpResponseRedirect('/')

@csrf_exempt
def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        email = request.POST['email']
        user = newlife_users.objects.create_user(username, email, password)
        if user is not None:
            user.is_active=False
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt+username).hexdigest()
            user.activation_key=activation_key
            user.save()
            # email
            mail_list = []
            title = "This is a Activation email"
            message = "Hello! %s \n This is the active url: http://127.0.0.1:8000/activate/%s"%(user, activation_key)
            sender = "wuyue92tree@163.com"
            reciver = user.email
            mail_list.append(reciver)
            try:
                send_mail(subject=title,
                        message=message,
                        from_email=sender,
                        recipient_list=mail_list,
                        fail_silently=False,
                        connection=None
                            )
                return render_to_response('notice/register_success.html')
            except:
                user.delete()
                return render_to_response('notice/register_error.html')
        else:
            return render_to_response('notice/register_error.html')
    else:
        return render_to_response('account/new_account.html', context_instance=RequestContext(request))

def activate(request, activation_key):
    SHA1_RE = re.compile('^[a-f0-9]{40}$')
    if SHA1_RE.search(activation_key):
        try:
            data = newlife_users.objects.get(activation_key=activation_key)
            if data:
                data.is_active=True
                data.activation_key="ACTIVATED"
                data.save()
                return render_to_response('notice/activation.html', RequestContext(request, locals()))
        except:
            return render_to_response('notice/404.html', RequestContext(request, locals()))


def user_settings(request):
    user = request.user
    return render_to_response('user_settings.html', locals())

def users_list(request):
    user = request.user
    users = newlife_users.objects.all()
    for username in users:
        return render_to_response('users.html', locals())

